#!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File    :   InstallFont.py
@Time    :   2023-03-28 16:57
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   liumou.site@qq.com
@Homepage : https://liumou.site
@Desc    :   Linux字体安装
"""
import os
import sys
from argparse import ArgumentParser
from subprocess import getoutput

from loguru import logger


class BuildDeb:
	def __init__(self, arm64=True, amd64=True, mips64=False, git=None, html=None):
		"""
		自动构建deb包
		:param arm64: 构建arm包
		:param amd64: 构建amd包
		:param mips64: 构建mips包
		"""
		self.html = html
		try:
			with open(file="ver.txt", mode='r', encoding="utf8") as r:
				self.version = r.read()
		except Exception as e:
			logger.error(str(e))
			logger.error("版本获取失败")
			sys.exit(2)

		self.git = git
		self.work = os.getcwd()
		self.mips64 = mips64
		self.amd64 = amd64
		self.arm64 = arm64
		self.home = os.getenv("HOME")
		self.pack_root = "包所在目录"
		self.debian = ""
		self.postinst = ""
		self.postrm = ""
		self.preinst = ""
		self.control = ""
		self.pack_apps = ""
		self.build_apps_pack = "源码包路径,例如: /root/com.liumou.inode/"
		self.files = "源码包files文件夹路径,例如: /root/com.liumou.inode/files"
		self.shell_kylin = "麒麟系统专属脚本所在目录"
		self.shell_uos = "uos系统脚本所在目录"
		self.text = ""
		self.html_root = "/html"
		if not os.path.isdir(self.html_root):
			self.html_root = "/html"
		if not os.path.isdir(self.html_root):
			logger.error(f"路径不存在: {self.html_root}")
			exit(2)
		self.client = ""
		self.build_client = ""
		self.dst = os.path.join(self.html_root, self.client)
		self.client_latest = ""
		self.clt_ver = os.path.join(self.html_root, "version.html")
		self.set_build_arch = "amd64"
		self.set_file_arch = "x86_64"
		self.arch = getoutput("uname -m")
		if self.arch == "aarch64" or self.arch == "arm64":
			self.arch = "arm64"
		else:
			if self.arch == "mips64" or self.arch == "mips64le":
				self.arch = "mips64le"
			else:
				if str(self.arch).lower() == "x86_64".lower() or str(self.arch) == "amd64" or str(self.arch) == "x86":
					self.arch = "X86_64"
		self.build_arch_list = ["liumou"]
		self.publish_list = []
		self.init()
		self.src = ""
		self.dst = ""

	def _init_ver(self):
		logger.info(f"当前设置版本: {self.version}")
		self.client = f"com.liumou.inode_linux-all-{self.version}.deb"
		self.build_client = os.path.join(self.home, f"com.liumou.inode_{self.version}.deb")
		self.pack_root = os.path.join(self.home, f"com.liumou.inode_{self.version}")
		self.debian = os.path.join(self.pack_root, "DEBIAN")
		self.control = os.path.join(self.pack_root, "DEBIAN/control")
		self.pack_apps = os.path.join(self.pack_root, "opt/apps")
		self.postinst = os.path.join(self.debian, "postinst")
		self.postrm = os.path.join(self.debian, "postrm")
		self.preinst = os.path.join(self.debian, "preinst")
		self.pack_apps = os.path.join(self.pack_root, "opt/apps")
		self.build_apps_pack = os.path.join(self.pack_apps, "com.liumou.inode")
		self.files = os.path.join(self.build_apps_pack, "files", "python")
		self.shell_kylin = os.path.join(self.files, "shell/kylin")
		self.shell_uos = os.path.join(self.files, "shell/uos")

	def init(self):
		self._init_ver()

		if not os.path.isdir(self.html_root):
			os.system(f"mkdir -p {self.html_root}")
		if os.path.isdir(self.pack_root):
			os.system(f"rm -rf {self.pack_root}")
		cp = f"cp -rf ./build/com.liumou.inode {self.pack_root}"
		print(cp)
		os.system(cp)
		if self.arm64:
			self.build_arch_list.append("arm64")
		if self.amd64:
			self.build_arch_list.append("amd64")
		if self.mips64:
			self.build_arch_list.append("mips64le")
		self.build_arch_list.remove("liumou")

	def write_ver(self):
		"""
		写入版本文件
		:return:
		"""
		try:
			with open(file=self.clt_ver, mode="w", encoding="utf8") as w:
				w.write(self.version)
		except Exception as e:
			logger.error(str(e))

	def write(self):
		"""
		写入控制文件信息
		:return:
		"""
		# if self.set_build_arch == "X86_64":
		# 	self.set_build_arch = "amd64"
		# if self.set_build_arch == "mips64le":
		# 	self.set_build_arch = "mips64el"
		txt = f"""Package: com.liumou.inode
Version: {self.version}
Section: utils
Priority: optional
Depends: 
Architecture: all
Homepage: https://liumou.site
Maintainer: 坐公交也用券 <liumou.site@qq.com>
Description: 这是用于处理Linux文件系统inode占用异常的工具\n"""
		try:
			with open(file=self.control, mode='w', encoding="utf8") as w:
				w.write(txt)
		except Exception as e:
			logger.error(str(e))
			sys.exit(3)
		self.set_build_arch = "all"

	def chmod(self):
		logger.debug('正在授权...')
		os.chdir(self.files)
		print(os.getcwd())
		os.system("chmod 0755 *.py")
		for f in [self.preinst, self.control, self.postinst, self.postrm]:
			if not os.path.isfile(f):
				c = f"cp -fr {self.git}/build/com.liumou.inode/DEBIAN/{os.path.basename(f)} {f}"
				print(c)
				os.system(c)
			if not os.path.isfile(f):
				print("文件不存在: ", f)
				sys.exit(4)
			os.system(f"chmod 0755 {f}")
		os.system(f"chmod -R 0755 {self.debian}")
		if os.path.isdir(self.shell_kylin):
			os.system(f"chmod 0777 {self.shell_kylin}/*")
		if os.path.isdir(self.shell_uos):
			os.system(f"chmod 0777 {self.shell_uos}/*")

	def latest(self):
		"""
		发布最新版
		:return:
		"""
		os.chdir(self.home)
		c = f"cp -rf {self.dst} {self.client_latest}"
		logger.info(f"正在发布最新版: {c}")
		if os.system(c) == 0:
			logger.info("最新版发布成功")
		else:
			logger.warning("最新版发布失败")

	def build(self):
		logger.info("文件信息如下")
		p = os.path.join(self.home, f"com.liumou.inode_{self.version}/opt/apps/com.liumou.inode/files/")
		print(os.listdir(p))
		os.chdir(self.home)
		logger.debug(f"当前目录：{os.getcwd()}")
		c = f"dpkg-deb -b -Z gzip {os.path.basename(str(self.pack_root))}"
		logger.info(f"执行: {c}")
		if os.system(c) == 0:
			logger.info("构建成功")
		else:
			logger.error("构建失败")
			sys.exit(2)
		if os.system(f"rm -f {self.dst}") != 0:
			print(f"rm -f {self.dst}")
			logger.error("删除失败: ", self.dst)
			sys.exit(2)

	def to_html(self):
		"""
		发布到网站
		:return:
		"""

		self.client = f"com.liumou.inode_all-linux_{self.version}.deb"
		self.client_latest = os.path.join(self.html_root, f"com.liumou.inode_linux-all_latest.deb")
		self.dst = os.path.join(self.html_root, "Release", self.client)
		src = os.path.join(self.home, f"com.liumou.inode_{self.version}.deb")
		c = f"cp -rf {src} {self.dst}"
		if os.system(c) == 0:
			self.dst = os.path.join(self.git, "Release", self.client)
			os.chdir(self.git)
			c = f"cp -rf {src} {self.dst}"
			os.system(c)
			os.system(f"git add {self.dst}")
			os.system("git commit -m 'Release'")
			os.system("git push")
			logger.info("复制成功")
			self.publish_list.append(f"http://clt.liumou.site/Release/{self.client}")
			self.publish_list.append(f"http://clt.liumou.site/{os.path.basename(self.client_latest)}")
		else:
			logger.error("发布失败")
			print(c)

	def install(self):
		logger.debug(f"{self.set_build_arch} : {self.arch}")
		if self.set_build_arch == self.arch:
			c = f"dpkg -i {self.build_client}"
			print(c)
			if os.system(c) == 0:
				print("安装成功")
				return True
			return False
		logger.debug("跳过安装")

	def delete(self):
		"""
		删除残留文件
		:return:
		"""
		logger.debug("正在删除残留文件")
		rl = [f"rm -fr {self.pack_root}", f"rm -f {self.build_client}", "rm -f com.liumou.inode_*.zip"]
		for i in rl:
			print(i)
			os.system(i)

	def start(self):
		"""
		开始
		:return:
		"""
		pwd = os.getcwd()
		pwd = os.getcwd()
		os.chdir(pwd)
		self.chmod()
		self.write_ver()
		self.build_arch_list = ["all"]
		for i in self.build_arch_list:
			self.set_build_arch = i
			self.set_file_arch = i
			self.write()
			self.chmod()
			self.build()
			self.install()
			self.to_html()
			self.latest()
		self.delete()
		print("发布清单")
		if len(self.publish_list) >= 1:
			for i in self.publish_list:
				print(i)


if __name__ == "__main__":
	g = os.getcwd()
	c = "/home/ml/client/"
	arg = ArgumentParser(description='自动化打包', prog="布尔传参")
	arg.add_argument('--debug', action='store_true', help='Enable debug mode')
	arg.add_argument('-g', '--git', type=str, help=f"设置项目源码路径,默认: {g}", default=g, required=False)
	arg.add_argument('-c', '--client', type=str, help=f"设置发布路径,默认: {c}", default=c, required=False)
	args = arg.parse_args()
	args_d = args.debug
	args_g = args.git
	args_c = args.client
	os.chdir(args_g)
	os.system("git pull")
	bb = BuildDeb(arm64=True, amd64=True, mips64=True, git=g, html=args_c)
	bb.start()
